package com.example.servlet;
import com.example.dao.StudentMapper;
import com.example.pojo.Student;
import com.example.pojo.StuClass;
import com.example.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //获取前端的学生参数
        String stuName = request.getParameter("stu_name");
        int stuNo = Integer.parseInt(request.getParameter("stu_no"));
        String class_name = request.getParameter("class_name");

        Student student = new Student();
        student.setStu_name(stuName);
        student.setStu_no(stuNo);

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
            //通过class_name获取class_id
            StudentMapper studentDao = sqlSession.getMapper(StudentMapper.class);
            StuClass stuClass = studentDao.getClassByName(class_name);
            if (stuClass != null) {
                student.setClass_id(stuClass.getClass_id());
                studentDao.addStudent(student);
                sqlSession.commit();
                // 重定向到学生列表页面或其他页面
                response.sendRedirect("home.jsp");
            } else {
                response.getWriter().println("班级没找到");
            }
        } finally {
            sqlSession.close();
        }
    }
}
